import SingleBase from '../base/SingleBase';
import {cUI} from '../../config/Config';

const {ccclass, property} = cc._decorator;
@ccclass
export default class Sound extends SingleBase {
    music_switch: boolean = true;
    effect_switch: boolean = true;
    music_volume: number = 1;
    effect_volume: number = 1;
    now_music: string;
    effect_list: Map = new Map<string, number>();
    toggleMusic() {
        this.music_switch = !this.music_switch;
        this.music_switch ? cc.audioEngine.resumeMusic() : cc.audioEngine.pauseMusic();
    }
    toggleEffect() {
        this.effect_switch = !this.effect_switch;
        if(!this.effect_switch) cc.audioEngine.stopAllEffects();
    }
    isPlaying(id: number) {
        return cc.audioEngine.getState(id) === cc.audioEngine.AudioState.PLAYING;
    }
    async playEffect(url: string, is_clear: boolean = false) {
        if (!url || !this.effect_switch || this.effect_volume <= 0) {
            return;
        }
        // if(this.effect_list.has(url)) {
        //     let id = this.effect_list.get(url);
        //     if (this.isPlaying(id)) {
        //         if (!is_clear) {
        //             return;
        //         }
        //         cc.audioEngine.stopEffect(id);
        //     }
        // }
        // console.log('playEffect ' + url);
        let res = await cUI.loadRes(url, cc.AudioClip);
        let id = cc.audioEngine.playEffect(res, false);
        this.effect_list.set(url, id);
    }



    async playMusic(url: string, volume: number = this.music_volume) {
        if (!this.music_switch || url === this.now_music || this.music_volume <= 0) {
            return;
        }
        cc.audioEngine.stopMusic();
        this.now_music = url;
        let res = await cUI.loadRes(url, cc.AudioClip);
        this.setMusicVolume(volume);
        cc.audioEngine.playMusic(res, true);
    }
    setMusicVolume(volume: number) {
        this.music_volume = volume;
        cc.audioEngine.setMusicVolume(volume);
    }
    setEffectVolume(volume: number) {
        this.effect_volume = volume;
        cc.audioEngine.setEffectsVolume(volume);
    }
    isMusicPlaying() {
        cc.audioEngine.isMusicPlaying();
    }
    pauseMusic() {
        cc.audioEngine.pauseMusic()
    }
    resumeMusic() {
        cc.audioEngine.resumeMusic();
    }
}